﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using MP.Core.Config;
using MP.Core.Library;
using System.Data.SqlClient;

namespace MP.Core.Authentication.Page
{
    public class AuthenticationBase : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            string themes = "";
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["themes"]))
                themes = ConfigurationManager.AppSettings["themes"];

            switch (themes)
            {
                case "BlueSky":
                    Page.Theme = themes;
                    break;
                case "Lunar2011":
                    Page.Theme = themes;
                    Page.MasterPageFile = "~/MasterPage/Lunar2011" + Page.MasterPageFile;
                    break;
                default:
                    Page.Theme = "BlueSky";
                    break;
            }
        }

        public string ModuleID
        {
            get { return ViewState["ModuleID"] != null ? ViewState["ModuleID"].ToString() : ""; }
            set { ViewState["ModuleID"] = value; }
        }

        public Breadcrumb navi { get; set; }
        

        #region "Override Method"
        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                ModuleID = GetModuleId();
                LogPage();
            }

            if (ModuleID != ".")
            {

                if (string.IsNullOrEmpty(Util.CurrentUserName))
                {
                    Response.Redirect(EnumAuthentication.PageRedirect + "?returnUrl=" + Request.RawUrl);
                }
                else
                {
                    MembershipUser user = Membership.GetUser(Util.CurrentUserName);
                    if (user != null && !user.IsApproved)
                        Response.Redirect(EnumAuthentication.PageRedirect + "?returnUrl=" + Request.RawUrl);
                }
            }

            navi = new Breadcrumb(Page);
            navi.Init();
            
            base.OnLoad(e);
        }
        #endregion

        #region "Public Method"
        public bool CheckRoles(string Module, string Action)
        {
            return MPRoleProvider.CreateInstant().CheckRoles(Util.CurrentUserName, Module, Action);
        }

        public void RedirectLogin()
        {
            Response.Redirect(EnumAuthentication.PageRedirect);
        }

        public bool IsShow()
        {
            return CheckRoles(ModuleID, EnumActions.SHOW);
        }

        public bool IsAdd()
        {
            return CheckRoles(ModuleID, EnumActions.ADD);
        }

        public bool IsEdit()
        {
            return CheckRoles(ModuleID, EnumActions.EDIT);
        }

        public bool IsDelete()
        {
            return CheckRoles(ModuleID, EnumActions.DELETE);
        }

        public bool IsEnable()
        {
            return CheckRoles(ModuleID, EnumActions.ENABLE);
        }

        public bool IsDisable()
        {
            return CheckRoles(ModuleID, EnumActions.DISABLE);
        }

        public bool IsAdd(string tableName, string recordId)
        {
            return IsAdd();
        }

        public bool IsEdit(string tableName, string recordId)
        {
            return IsEdit();
        }

        public bool IsShow(string tableName, string recordId)
        {
            return IsShow();
        }

        public bool IsDelete(string tableName, string recordId)
        {
            return IsDelete();
        }

        #endregion

        #region Private Method
        string GetModuleId()
        {
            string id = this.GetType().ToString();
            string strSQL = "PRC_GetModulePage";
            SqlParameter[] param = new SqlParameter[3];
            param[0] = new SqlParameter("@pageId", id);
            param[1] = new SqlParameter("@pageUrl", Page.Request.Url.AbsolutePath);
            bool isUpdate = false;
            if (!string.IsNullOrEmpty(Page.Request["updatepage"]) && Page.Request["updatepage"] == "1")
                isUpdate = true;
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["updatepage"]) && ConfigurationManager.AppSettings["updatepage"] == "1")
                isUpdate = true;
            param[2] = new SqlParameter("@update", isUpdate);
            DataTable tbl = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
            if (tbl != null && tbl.Rows.Count > 0)
            {
                return tbl.Rows[0]["ModCode"].ToString();
            }
            return "";
        }

        void LogPage()
        {
            if (!string.IsNullOrEmpty(Util.CurrentUserName))
            {
                string id = this.GetType().ToString();
                string strSQL = "PRC_LogPage";
                Guid mBranchId = Guid.Empty;
                DataTable tbl = GetProfiles();
                if (tbl != null && tbl.Rows.Count > 0)
                {
                    if (!Convert.IsDBNull(tbl.Rows[0]["BranchId"]) && !string.IsNullOrEmpty(tbl.Rows[0]["BranchId"].ToString()))
                        mBranchId = new Guid(tbl.Rows[0]["BranchId"].ToString());
                }
                SqlParameter[] param = new SqlParameter[6];
                param[0] = new SqlParameter("@PageCode", id);
                param[1] = new SqlParameter("@UserName", Util.CurrentUserName);
                param[2] = new SqlParameter("@ClientIP", Request.UserHostAddress);
                param[3] = new SqlParameter("@QueryParam", Request.Url.Query);
                param[4] = new SqlParameter("@BranchIdPage", FGuid.ToGuid(CookieManager.getCookie(Page, "cBranchId")));
                param[5] = new SqlParameter("@BranchIdUser", mBranchId);
                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
            }
        }

        DataTable GetProfiles()
        {
            string strSQL = "Hr_Profiles";
            SqlParameter param = new SqlParameter("@username", Util.CurrentUserName);
            return SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
        }
        #endregion

    }
}
